package com.pangda.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.pangda.common.config.OSSAliyunFileStorageService;
import com.pangda.common.domain.ResponseResult;
import com.pangda.common.utils.FileUtil;
import com.pangda.common.utils.UserContext;
import com.pangda.pojo.Clue;
import com.pangda.pojo.data.ClueData;
import com.pangda.pojo.data.SysRoleData;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import java.util.List;

@RestController
@Api(tags = "通用")
public class CommonController {

    @Autowired
    private OSSAliyunFileStorageService oss;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/common/upload")
    public ResponseResult upload(@RequestPart("file") MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        // 获得文件扩展名
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String s = UUID.randomUUID().toString() + extension;
        redisTemplate.opsForValue().set(UserContext.getUser(), null);
        String upload = oss.upload(s, file.getInputStream());
        //返回文件地址 存入redis
        redisTemplate.opsForValue().set(UserContext.getUser(), upload);
        return ResponseResult.success(upload);
    }

    @GetMapping("/common/download")
    public void download(HttpServletResponse response, String fileName) throws IOException, ClassNotFoundException {
        if ("clues.xlsx".equals(fileName)) {
            FileUtil.getTemplate(response, "clues", ClueData.class);
        }
        String json = redisTemplate.opsForValue().get(fileName) + "";
        Map<String, Object> map = JSONUtil.parseObj(json);
        String o = (String) map.get("class");
        Class aClass = Class.forName(o);
        String listStr = (String) map.get("data");
        List list = JSONUtil.toList(listStr, aClass);
        FileUtil.downloadUnfilledToXlsx(fileName, response, aClass, list);
        redisTemplate.delete(fileName);
    }
}
